package main

import (

	"fmt"
	"net"
	"os"
)

var conns map[string]net.Conn

func init(){
	conns =make(map[string]net.Conn)
}

func handleRequest(conn net.Conn) {
	ipStr := conn.RemoteAddr().String()
	conns[ipStr]=conn
	defer func() {
		fmt.Println("Disconnected :" + ipStr)
		conn.Close()
		delete(conns, ipStr)
	}()

	var buf = make([]byte, 10240)

	for {
		n, err := conn.Read(buf)
    if err != nil {
        return
    }

		for k, v := range conns {
		  if k != ipStr{
				v.Write(buf[0:n])
			}
		}

	}

	fmt.Println("Done!")
}

func main() {

	// port := *flag.String("port", ":6060", "run port")
	port := "9999"
	args := os.Args
	if args == nil || len(args) < 2 {

	} else {
		port = args[1]
	}

	listen, err := net.Listen("tcp", ":" + port)

	if err != nil {
		fmt.Println("Error listening:", err)
		os.Exit(1)
	}
	defer listen.Close()

	fmt.Println("Listening on " + port)

	for {
		// 接收一个client
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err)
			os.Exit(1)
		}

		fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())

		// 执行
		go handleRequest(conn)
	}
}
